﻿using DevLib.TestCase;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


/** 
 ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** **
 * Description: 
 * Author: Heller (HellerSong@outlook.com)
 * CreationTime: 3/24/2015 7:57:08 AM
 ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** 
 **/
namespace DevLib.SuperTool
{
	public class ProcessOM
	{
		public static String EXE_NOTEPAD = "notepad.exe";
		public static String EXE_IE = "iexplore.exe";
		public static String EXE_CMD = "cmd.exe";
		public static String EXE_EXCEL = "excel.exe";

		private static Process currentProcess = null;


		private ProcessOM() { }


		public static void Launch(String exeFileName, params String[] parameters)
		{
			StrCheck.CheckChainArgUsable(exeFileName);

			// Fill the process info that pending to start
			ProcessStartInfo psi = new ProcessStartInfo(exeFileName);

			// Set start arguments if there is
			if (parameters.Length > 0)
				for (int i = 0; i < parameters.Length; i++)
					psi.Arguments += parameters[i] + " ";	// Each splited by space

			// Execute the *.exe procedure
			currentProcess = Process.Start(psi);
		}
		public static String LaunchCmd(String parameters)
		{
			StrCheck.CheckChainArgUsable(parameters);

			String executeResult = null;

			ProcessStartInfo psi = new ProcessStartInfo(EXE_CMD);
			// Argument "/c" will exit cmd window when finish, "/k" will not exit
			psi.Arguments = "/c " + parameters;
			psi.RedirectStandardOutput = true;
			psi.UseShellExecute = false;

			Process p = Process.Start(psi);
			p.WaitForExit();
			// if you want use StandardOutput, redirected should enable ahead in psi
			executeResult = p.StandardOutput.ReadToEnd();

			return executeResult;
		}

		public static void CloseCurrentProcess()
		{
			if (currentProcess != null && !currentProcess.HasExited)
				currentProcess.Kill();
		}

		/// <summary> Really pay attention! This will destroy all thread without saving. </summary>
		public static void Destroy(String exeName)
		{
			StrCheck.CheckChainDirIllegal(exeName);

			foreach (Process p in Process.GetProcesses())
				if (exeName.Contains(p.ProcessName))
					p.Kill();
		}


		// Some instresting test, haha
		public static void test1()
		{
			test2();
		}
		public static void test2()
		{
			test1();
		}


	}

}
